package com.educhains.web.interceptor;

import com.educhains.module.user.vo.User;
import com.educhains.web.util.SessionUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author YuRun
 * @since 2017年11月3日
 */
public class EduchainsHandleShakeInterceptor implements HandshakeInterceptor {

    /**
     * Before hand shake
     *
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return
     * @throws Exception
     */
    public boolean beforeHandshake(ServerHttpRequest request,
                                   ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) throws Exception {
        System.out.println("========== EduchainsHandleShakeInterceptor: beforeHandshake  ==========" + attributes);

        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpSession session = servletRequest.getServletRequest().getSession(false);
            // 标记用户
            User user = (User) session.getAttribute("sessionUser");
            if (user != null) {
                attributes.put("userId", user.getUserId()); //为服务器创建WebSocketSession做准备
                System.out.println("用户id：" + user.getUserId() + " 被加入");
            } else {
                return false;
            }
        }
        return true;
    }


    /**
     * After hand shake
     *
     * @param request
     * @param response
     * @param wsHandler
     * @param ex
     */
    public void afterHandshake(ServerHttpRequest request,
                               ServerHttpResponse response, WebSocketHandler wsHandler,
                               Exception ex) {
        System.out.println("========== EduchainsHandleShakeInterceptor: afterHandshake  ==========");
        //super.afterHandshake(request, response, wsHandler, ex);
    }
}
